﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Activation;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;

namespace TaxonomyService.ISAPI
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class TaxonomyService : ITaxonomyService
    {
        #region ITaxonomyService Members

        public Boolean SetTaxonomy(string docName, string termValue)
        {
            String siteName = "TaxonomySite";
            String listName = "Taxonomy Document Library";
            SPSite site = SPContext.Current.Site;
            SPWeb web = site.RootWeb;

            TaxonomySession taxonomySession = new TaxonomySession(site);
            TermStore termStore = taxonomySession.TermStores["Managed Metadata Service"];
            Group group = termStore.Groups["Site Collection - moss2010-hn"];
            TermSet termSet = group.TermSets["Company Term Set"];
            Term term = termSet.Terms[termValue];
            SPList list = site.AllWebs[siteName].Lists[listName];
            if (list != null)
            {
                TaxonomyField taxonomyField = list.Fields["Taxonomy Column"] as TaxonomyField;
                SPListItemCollection items = list.GetItems(new SPQuery()
                {
                    Query = @"<Where>
                        <Eq>
                            <FieldRef Name='LinkFilename' />
                            <Value Type='Text'>" + docName + @"</Value>
                        </Eq>
                        </Where>"
                });

                if (items.Count > 0)
                {
                    SPListItem item = items[0];

                    taxonomyField.SetFieldValue(item, term);
                    item.Update();
                    list.Update();
                }
                else
                {
                    return false;
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion
    }
}
